package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.dto.PageDTO;
import com.leyou.common.exception.LyException;
import com.leyou.item.dto.BrandDTO;
import com.leyou.item.entity.Brand;
import com.leyou.item.entity.CategoryBrand;
import com.leyou.item.mapper.BrandMapper;
import com.leyou.item.service.BrandService;
import com.leyou.item.service.CategoryBrandService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class BrandServiceImpl extends ServiceImpl<BrandMapper, Brand> implements BrandService {


    private final CategoryBrandService categoryBrandService;

    public BrandServiceImpl(CategoryBrandService categoryBrandService) {
        this.categoryBrandService = categoryBrandService;
    }


    @Override
    public PageDTO<BrandDTO> queryBrandByPage(Integer page, Integer rows, String key) {
        // 1.分页信息的健壮性处理
        page = Math.min(page, 100);
        rows = Math.max(rows, 5);
        // 2.分页
        Page<Brand> info = new Page<>(page, rows);

        //判断key是否为空，不为空返回true
        boolean isKeyExists = StringUtils.isNotBlank(key);

        //分页查询,queryBrandByPage 调用其兄弟方法
        // 4.如果key存在，添加like和eq的查询条件，否则不添加
        Page<Brand> brandPage = query().like(isKeyExists, "name", key)
                .or()
                .eq(isKeyExists, "letter", key)
                .page(info);


        //封装分页查询的结果，三个，总元素个数，总页面数，当前页的数据
        return new PageDTO<>(brandPage.getTotal(), brandPage.getPages(), BrandDTO.convertEntityList(brandPage.getRecords()));
    }

    @Override
    public List<BrandDTO> queryBrandByCategory(Long cid) {


        //根据分类的id在中间表中查询对应的品牌id的集合
        List<Long> brandIds =
                this.categoryBrandService
                        .query()
                        .eq("category_id", cid)
                        .list()
                        .stream()
                        .map(CategoryBrand::getBrandId)
                        .collect(Collectors.toList());


        //根据品牌的id集合查询对应的品牌集合
        return BrandDTO.convertEntityList(listByIds(brandIds));
    }

    /**
     * 5系列
     * @param name
     * @param letter
     * @param categoryIds
     * @param image
     */
    @Transactional
    @Override
    public void addBrand(String name, String letter, String categoryIds, String image) {

        Brand brand = new Brand();
        brand.setName(name);
        brand.setImage(image);
        brand.setLetter(letter.charAt(0));//"H"

        //保存品牌,同时主键回显
        boolean result = this.save(brand);

        //没有保存成功
        if (!result){
            throw new LyException(500,"品牌保存失败");
        }

        if (StringUtils.isBlank(categoryIds)){
            throw new LyException(400,"品牌保存失败");
        }

        //切分分类ids的字符串
        saveCategoryBrand(categoryIds, brand);
    }

    @Transactional
    @Override
    public void updateBrand(Long id,String name, String letter, String categoryIds, String image) {
        Brand brand = new Brand();
        brand.setId(id);
        brand.setName(name);
        brand.setImage(image);
        brand.setLetter(letter.charAt(0));//"H"

        //根据品牌id修改对应的品牌信息
        boolean result = updateById(brand);

        //没有修改成功
        if (!result){
            throw new LyException(500,"品牌修改失败");
        }

        //根据品牌的id查询品牌和分类的对应关系,delete * from tb_category_brand where brand_id = xxx
        result = this.categoryBrandService.remove(
                new QueryWrapper<CategoryBrand>()
                        .eq("brand_id",brand.getId()));

        //没有删除成功
        if (!result){
            throw new LyException(500,"品牌分类中间表关系删除失败");
        }
        saveCategoryBrand(categoryIds, brand);

    }

    private void saveCategoryBrand(String categoryIds, Brand brand) {
        boolean result;//切分分类ids的字符串
        String[] cids = categoryIds.split(",");

        List<CategoryBrand> categoryBrands = new ArrayList<>();

        //循环分类id的字符串数组，生成新的categoryBrand对象
        for (String cid : cids) {
            categoryBrands.add(CategoryBrand.of(Long.valueOf(cid), brand.getId()));
        }


        //批量保存categoryBrand
        result = this.categoryBrandService.saveBatch(categoryBrands);

        if (!result) {
            throw new LyException(500, "品牌分类关系保存失败");
        }
    }
}
